#! /usr/bin/env python3
# _*_coding:utf-8 _*_
# from __future__ import absolute_import, unicode_literals
# from celery import shared_task
from django.core.exceptions import FieldError
import json
import traceback
from django.db.models import Q

from repository import models

"""user_info表相关操作"""

# @shared_task
def get_users(*fields,**conditions):
    """传入条件，查询user表
    Args:
       conditions: 查询条件字典,如:{'username':'aaa'}
       fields: 返回结果中包含的字段列表，如['username','age']

    Return:
        res: {
          'status': 200,    # 状态码，200为正常返回；400为入参错误
          'data': [],    query_set列表
          'detail': ''    # 错误详情
        }

    """
    res = {
        'status': 200,
        'data': [],
        'detail': ''
           }
    try:
        query_res = list(models.UserInfo.objects.filter(**conditions).order_by('code').values(*fields).all())
    except FieldError:
        res['status'] = 400
        res['detail'] = '入参错误'
    else:
        res['data'] = query_res
    return json.dumps(res)


def save_user(instance=None,fields=None,**validated_data):
    """create或update操作
        Args:
            instance: 原实例，update用
            fields: 返回哪些字段给前端
            validated_data: 传入的合法数据
    """
    res = {
        'status': 200,
        'data': [],
        'detail': ''
           }
    try:
        if not fields:
            fields = []
        if not instance:  # 新增
            user_obj = models.UserInfo.objects.create(**validated_data)
            pk = user_obj.id
        else:    # 修改
            pk = instance.pop('id')
            models.UserInfo.objects.filter(id=pk).update(**validated_data)
        query_set = models.UserInfo.objects.filter(id=pk).values(*fields).first()

    except FieldError:
        res['status'] = 400
        res['detail'] = '入参错误'
    except Exception as e:
        print(e)
        res['status'] = 500
        res['detail'] = '系统错误'
    else:
        res['data'] = dict(query_set)
    return json.dumps(res)


def get_user_info(*filter_fields,**conditions):
    """获取某一个用户信息"""
    res = {
        'status': 200,
        'data': [],
        'detail': ''
       }
    try:
        query_res = models.UserInfo.objects.filter(**conditions).values(*filter_fields).first()
    except Exception:
        res['status'] = 501
        res['detail'] = '系统错误'
    else:
        res['data'] = query_res
    # print(res)
    return json.dumps(res)


def if_user_duplicate(pk,code):
    """更新员工信息前，判断code是否和其他员工重复"""
    res = {
        'status': 200,
        'data': [],
        'detail': ''
       }
    try:
        res['data'] = models.UserInfo.objects.filter(~Q(id=pk) & Q(code=code)).exists()
    except Exception:
        traceback.print_exc()
        res['status'] = 500
        res['detail'] = '系统错误'
    return json.dumps(res)


def delete_user(pk):
    """传入pk，删除用户"""
    res = {
        'status': 200,
        'data': [],
        'detail': ''
       }
    try:
        models.UserInfo.objects.filter(id=pk).delete()
    except Exception as e:
        traceback.print_exc()
        res['status'] = 501
        res['detail'] = '系统错误'
    return json.dumps(res)
